<template>
  <div class="money-range-input">
    <!-- 最小金额输入框 -->
    <el-input
      v-model="minValueRaw"
      placeholder="最小金额"
      clearable
      @blur="handleBlur('min')"
      @focus="handleFocus('min')"
      @input="validateMin"
    />
    <span class="separator">~</span>
    <!-- 最大金额输入框 -->
    <el-input
      v-model="maxValueRaw"
      clearable
      placeholder="最大金额"
      @blur="handleBlur('max')"
      @focus="handleFocus('max')"
      @input="validateMax"
    />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';

const props = defineProps({
  modelValue: { type: Array, default: () => null }
});

const emit = defineEmits(['update:modelValue']);

// 存储原始值（未格式化）
const minValueRaw = ref('');
const maxValueRaw = ref('');

// 金额格式化函数（添加千分位）
const formatMoney = (value) => {
  if (!value) return '';
  const parts = value.toString().split('.');
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return parts.join('.');
};

// 去除格式化（还原为数字字符串）
const unformatMoney = (value) => {
  return value.replace(/,/g, '');
};

// 失焦处理：格式化显示
const handleBlur = (type) => {
  if (type === 'min') {
    minValueRaw.value = formatMoney(minValueRaw.value);
  } else {
    maxValueRaw.value = formatMoney(maxValueRaw.value);
  }
  validateRange();
};

// 聚焦处理：还原纯数字
const handleFocus = (type) => {
  if (type === 'min') {
    minValueRaw.value = unformatMoney(minValueRaw.value);
  } else {
    maxValueRaw.value = unformatMoney(maxValueRaw.value);
  }
};

// 校验逻辑
const validateMin = () => {
  const min = unformatMoney(minValueRaw.value);
  const max = unformatMoney(maxValueRaw.value);
  if (min && max && Number(min) > Number(max)) {
    ElMessage.error('最小金额不能大于最大金额');
  }
  emitValue();
};

const validateMax = () => {
  validateMin(); // 复用校验逻辑
};

const validateRange = () => {
  const min = unformatMoney(minValueRaw.value);
  const max = unformatMoney(maxValueRaw.value);
  if (min && max && Number(min) > Number(max)) {
    ElMessage.error('区间无效：最小金额＞最大金额');
  }
};

// 提交父组件值（返回数字数组）
const emitValue = () => {
  const min = unformatMoney(minValueRaw.value) || 0;
  const max = unformatMoney(maxValueRaw.value) || null;
  emit('update:modelValue', [min ? Number(min) : null, max ? Number(max) : null]);
};

// 监听外部传入的modelValue
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    minValueRaw.value = newVal[0] !== null ? formatMoney(String(newVal[0])) : '';
    maxValueRaw.value = newVal[1] !== null ? formatMoney(String(newVal[1])) : '';
  }
}, { immediate: true });
</script>

<style scoped>
.money-range-input {
  display: flex;
  align-items: center;
}
.separator {
  margin: 0 10px;
  color: #888;
}
</style>